<?php
/**
 * Created by PhpStorm.
 * User: zxd
 * Date: 2016/11/18 0018
 * Time: 下午 8:40
 */

namespace App\Common;


use App\Models\WeixinToken;
use App\Weixin\WechatServiceClient;
use Illuminate\Support\Facades\Log;
use p5\objects\TimeUtils;

class WeixinTokenCacher
{

    static public function getAuthrizeInfo($appid)
    {
        $bean = self::loadParam(WechatServiceClient::COMPONENT_AUTHORIZATION_INFO, $appid);
        if ($bean->expired() || !$bean->hasValue()) {
            return false;
        }
        return $bean->get_parameter_value();
    }

    static public function getAuthrizeInfoBean($appid)
    {
        $bean = self::loadParam(WechatServiceClient::COMPONENT_AUTHORIZATION_INFO, $appid);
        if (!$bean->hasValue()) {
            return false;
        }
        return $bean;
    }

    static public function getPreAuthCode()
    {
        $bean = self::loadParam(WechatServiceClient::COMPONENT_PRE_AUTH_CODE);
        if ($bean->expired() || !$bean->hasValue()) {
            return false;
        }
        return $bean->get_parameter_value();
    }

    static public function getComponentVerifyTicket()
    {
        $bean = self::loadParam(WechatServiceClient::COMPONENT_VERIFY_TICKET);
        if ($bean->expired() || !$bean->hasValue()) {
            Log::debug(json_encode($bean));
            return false;
        }
        return $bean->get_parameter_value();
    }

    static public function getComponentAccessCode()
    {
        $bean = self::loadParam(WechatServiceClient::COMPONENT_ACCESS_TOKEN);
        if ($bean->expired() || !$bean->hasValue()) {
            return false;
        }
        return $bean->get_parameter_value();
    }

    static public function getComponentAccessTokenBean()
    {
        return self::loadParam(WechatServiceClient::COMPONENT_ACCESS_TOKEN);
    }

    /**
     * @param $companyId
     * @param $parameterName
     * @return WeixinToken
     */
    static public function loadParam($parameterName, $appid = "lintong")
    {
        $bean = new WeixinToken();
        $bean->set_appid($appid);
        $bean->set_parameter_name($parameterName);
        ModelCacher::resume($bean);
        return $bean;
    }

    /**
     * @param $bean WeixinToken
     */
    static public function persist($bean)
    {
        ModelCacher::replaceIntoDB($bean);
        self::cache($bean);
    }

    /**
     * @param $token WeixinToken
     */
    static public function cache($token)
    {
        ModelCacher::cache($token);
    }

}